package cn.geminis.resources.service.model;

import cn.geminis.core.exception.CommonException;
import cn.geminis.lowcode.annotation.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.vladmihalcea.hibernate.type.json.JsonType;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Type;
import org.springframework.util.StringUtils;

import java.util.Set;

/**
 * @author Allen
 */
@Getter
@Setter
@UuidEntity(prePersist = false)
@DynamicInsert
@DynamicUpdate
@QueryFilter
@CrudRepository
@CrudController(deleteInBatch = false)
public class Organization {

    @Column(nullable = false, length = 128)
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.Like)
    private String name;

    @Column(nullable = false)
    private String pathId;

    @Column(length = 36)
    @QueryFilterProperty
    @QueryFilterProperty(filterType = QueryFilterProperty.FilterType.IsNull)
    private String parentId;

    @Column(nullable = false, length = 36)
    private String type;

    @Column(nullable = false)
    private int showOrder;

    @Type(JsonType.class)
    @Column(columnDefinition = "json")
    private Object properties;

    @OneToMany(mappedBy = "organization", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    private Set<OrgUser> users;

    @Transient
    @JsonProperty
    private String parentPath;

    @PrePersist
    void setPathId() {
        this.setId();
        if (!StringUtils.hasText(this.parentPath)) {
            throw new CommonException("需要设置上级ID路径");
        }
        this.pathId = this.parentPath + this.getId() + "/";
    }
}
